package com.ruoyi.recyclecomprehensive.controller;


import cn.hutool.core.util.StrUtil;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.recycle.domain.MerchantManagement;
import com.ruoyi.recycle.dto.LoginDTO;
import com.ruoyi.recycle.service.IMerchantManagementService;
import com.ruoyi.recycle.vo.LoginVO;
import com.ruoyi.recyclecomprehensive.service.LoginService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.Objects;


@RequestMapping("/login")
@RestController
@Api(tags = "用户登录")
@Slf4j
public class LoginController extends BaseController {
    @Autowired
    private LoginService loginService;
    @Autowired
    private IMerchantManagementService merchantManagementService;

    @PostMapping
    @ApiOperation("登录接口")
    @SneakyThrows
    public R<LoginVO> login(@RequestBody LoginDTO loginDTO) {
        try {
            final LoginVO vo = loginService.login(loginDTO);
            return R.ok(vo);
        } catch (Exception e) {
            return R.fail(StrUtil.format("登录失败,原因:{}", e.getMessage()));
        }
    }

    @ApiOperation("微信授权获取用户openId")
    @GetMapping("/wechatAuth")
    public R<String> wechatAuth(@RequestParam String encryptedData, @RequestParam String iv, @RequestParam String code) {
        final Map<String, String> authMap = loginService.wechatAuth(code, encryptedData, iv);
        if (StrUtil.isNotEmpty(authMap.get("errmsg"))) {
            return R.fail(StrUtil.format("获取授权失败,原因:{}", authMap.get("errmsg")));
        } else {
            return R.ok(authMap.get("openId"));
        }

    }

    @ApiOperation("获取综合站账号信息")
    @GetMapping("/getUserInfo")
    @ApiImplicitParam(name = "merchantId", value = "综合站Id")
    public R<MerchantManagement> getUserInfo(@RequestParam Long merchantId) {
        final MerchantManagement info = merchantManagementService.getById(merchantId);
        if (Objects.nonNull(info)) {
            info.setPassword("");
            info.setMerchantPassword("");
        }
        return R.ok(info);
    }

    @GetMapping("/logout")
    @ApiOperation("用户注销")
    public R logout(HttpServletRequest request) {
        return loginService.logout(request);
    }

}
